<template>
  <form id="data-form-container" ref="formRef" @submit.prevent="handleSubmit" class="data-form-container">
    <div class="form-item">
      <div class="text-area">
        <textarea maxlength="80" placeholder="输入留言内容" v-model="formData.content"></textarea>

        <span class="tip">{{ formData.content.length }}/80</span>
      </div>
      <div class="error">{{ error.content }}</div>
    </div>
    <div class="form-item">
      <div class="input-area">
        <input type="text" maxlength="4" v-model="formData.nickname" placeholder="用户昵称" />
        <span class="tip">{{ formData.nickname.length }}/4</span>
      </div>
      <div class="error">{{ error.nickname }}</div>
    </div>
    <div class="form-item">
      <div class="input-area">
        <div class="verify">
          <input type="text" maxlength="4" v-model="formData.vCode" placeholder="输入验证码" />
          <div class="captchaImgRef" @click="getCaptcha" ref="captchaImgRef" />
        </div>
      </div>
      <div class="error">{{ error.vCode }}</div>
    </div>
    <div class="form-item">
      <div class="button-area">
        <button :disabled="isSubmiting">
          {{ verifyStatus ? '提交中...' : '提交' }}
        </button>
        <span class="btnTip" v-if="isSubmiting">{{ time }}秒</span>
      </div>
    </div>
  </form>
</template>

<script setup lang="ts">
import { reactive, ref, getCurrentInstance, onMounted, type ComponentInternalInstance } from 'vue'
import * as msgApi from '@/api/message'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const $emit = defineEmits(['submit'])
const formData = reactive({
  nickname: '',
  content: '',
  vCode: ''
})
const error = reactive({
  nickname: '',
  content: '',
  vCode: ''
})
const isSubmiting = ref(false)
const formRef = ref<any>(null)
const captchaImgRef = ref<any>(null)
const time = ref(0)
const flagTime = ref(60) //倒计时时间固定值
const verifyStatus = ref(false)
onMounted(async () => {
  await getCaptcha()
  handelInterval()
})

async function handleSubmit() {
  error.nickname = formData.nickname ? '' : '请填写昵称'
  error.content = formData.content ? '' : '请填写内容'
  error.vCode = formData.vCode ? '' : '请填写验证码'
  if (error.nickname || error.content || error.vCode) {
    // 有错误
    return
  }
  localStorage.setItem('startTime', new Date().getTime() + '')
  //校验验证码
  let resp = await msgApi.postVerifyCode({ captcha: formData.vCode })
  console.log(resp, '<---验证结果')
  //重新获取验证码
  getCaptcha()
  if (!resp) {
    proxy.$showMessage({
      content: '验证码错误',
      type: 'error',
      duration: 3000,
      container: formRef.value,
      callback: () => {
        sartClock(5)
        formData.vCode = ''
        isSubmiting.value = true // 正在提交，防止重复点击
      }
    })
    return
  }
  isSubmiting.value = true // 正在提交，防止重复点击
  formData.vCode = ''
  verifyStatus.value = true
  $emit('submit', formData, (successMsg: string) => {
    //失败回调
    if (!successMsg) {
      formData.nickname = ''
      formData.content = ''
      formData.vCode = ''
      verifyStatus.value = false
      sartClock(5)
      return
    }
    //成功回调
    proxy.$showMessage({
      content: successMsg,
      type: 'success',
      duration: 1000,
      container: formRef.value,
      callback: () => {
        formData.nickname = ''
        formData.content = ''
        formData.vCode = ''
        verifyStatus.value = false
        sartClock(60)
      }
    })
  })
}
//倒计时
function sartClock(duration = 5) {
  isSubmiting.value = true
  time.value = duration
  flagTime.value = duration
  let t = setInterval(() => {
    time.value--
    if (time.value < 0) {
      clearInterval(t)
      time.value = duration
      isSubmiting.value = false
    }
  }, 1000)
}
//验证码获取
async function getCaptcha() {
  let data = await msgApi.getCaptcha()
  if (captchaImgRef.value) {
    captchaImgRef.value.innerHTML = data
  }
}
//保持定时器
function handelInterval() {
  let startTime = localStorage.getItem('startTime')
  if (!startTime) return
  let diffTime = Math.floor((new Date().getTime() - Number(startTime)) / 1000)
  let result = flagTime.value - diffTime
  if (result > 0) {
    sartClock(result)
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/var.scss';

.data-form-container {
  margin-bottom: 20px;
  overflow: hidden;
}

.form-item {
  margin-bottom: 8px;
}

.input-area {
  width: 50%;
  position: relative;

  @media screen and (max-width: 992px) {
    width: 75%;
  }
}

.text-area {
  position: relative;
  display: flex;
}

.tip {
  position: absolute;
  right: 5px;
  bottom: 5px;
  color: #b4b8bc;
  font-size: 12px;
}

input,
textarea {
  display: block;
  width: 100%;
  box-sizing: border-box;
  border: 1px dashed $gray;
  outline: none;
  color: $words;
  font-size: 14px;
  border-radius: 4px;

  &:focus {
    border-color: $primary;
  }
}

input {
  padding: 0 15px;
  height: 40px;
}

textarea {
  resize: none;
  padding: 8px 15px;
  height: 120px;
}

.error {
  margin-top: 6px;
  color: $danger;
  font-size: 14px;
  height: 20px;
  line-height: 20px;
}

button {
  position: relative;
  cursor: pointer;
  border: none;
  outline: none;
  width: 100px;
  height: 34px;
  color: #fff;
  border-radius: 4px;
  background: $primary;

  &:hover {
    background: darken($primary, 10%);
  }

  &:disabled {
    background: lighten($primary, 20%);
    cursor: not-allowed;
  }
}

.button-area {
  display: flex;
  align-items: flex-end;

  .btnTip {
    margin-left: 10px;
    color: red;
    font-size: 12px;
  }
}

.verify {
  display: flex;
  align-items: center;

  input {
    border: 1px solid #ccc;
    width: 28%;

    @media screen and (max-width: 992px) {
      width: 43%;
    }
  }

  .captchaImgRef {
    width: 150px;
    height: 50px;
    background: #fff;
  }
}
</style>
